<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>任务计时器</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 800px;
      margin: 0 auto;
      padding: 20px;
      font-size: 14px;
    }

    .timer-form {
      background: #f5f5f5;
      padding: 20px;
      border-radius: 8px;
      margin-bottom: 20px;
    }

    .form-group {
      margin-bottom: 15px;
    }

    label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
    }

    input, select {
      width: 100%;
      padding: 8px;
      border: 1px solid #ddd;
      border-radius: 4px;
      box-sizing: border-box;
    }

    button {
      background: #007bff;
      color: white;
      padding: 10px 20px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }

    button:hover {
      background: #0056b3;
    }

    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 20px;
    }

    th, td {
      border: 1px solid #ddd;
      padding: 12px;
      text-align: left;
    }

    th {
      background-color: #f2f2f2;
    }

    .edit-btn {
      background: #28a745;
      padding: 5px 10px;
      font-size: 12px;
      margin-right: 5px;
    }

    .edit-btn:hover {
      background: #218838;
    }

    .delete-btn {
      background: #dc3545;
      padding: 5px 10px;
      font-size: 12px;
    }

    .delete-btn:hover {
      background: #c82333;
    }

    .notification {
      /*position: fixed;
      top: 20px;
      right: 20px;*/
      background: #28a745;
      color: white;
      padding: 15px;
      border-radius: 4px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
      display: none;
    }
  </style>
</head>
<body>
  <div class="timer-form">
    <div class="form-group">
      <label for="taskName">事项:</label>
      <input type="text" id="taskName" required>
    </div>

    <div class="form-group">
      <label for="lastExecution">最近执行时间:</label>
      <input type="datetime-local" id="lastExecution" step="1" required>
    </div>

    <div class="form-group">
      <label for="intervalMinutes">间隔时间(分钟):</label>
      <input type="number" id="intervalMinutes" min="1" value="5" required>
    </div>

    <button onclick="addTimer()">添加计时器</button>
  </div>
  <div class="notification" id="notification">
    <span id="notificationText"></span>
  </div>
  <table id="timersTable">
    <thead>
      <tr>
        <th>事项</th>
        <th>最近执行时间</th>
        <th>间隔时间(分钟)</th>
        <th>下次执行时间</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody id="timersList">
    </tbody>
  </table>

  <audio id="alertSound" preload="auto">
    <source src="media/bell-ringing-05.wav" type="audio/wav">
  </audio>

  <script>
    class TimerStorage {
      static STORAGE_KEY = 'timers_data';

      // 从 localStorage 加载定时器数据
      static loadTimers() {
        try {
          const data = localStorage.getItem(this.STORAGE_KEY);
          if (data) {
            const parsed = JSON.parse(data);
            // 将日期字符串转换回 Date 对象
            return parsed.map(timer => ({
              ...timer,
              lastExecution: new Date(timer.lastExecution),
              nextExecution: new Date(timer.nextExecution)
            }));
          }
        } catch (e) {
          console.error('加载定时器数据失败:', e);
        }
        return [];
      }

      // 保存定时器数据到 localStorage
      static saveTimers(timers) {
        try {
          localStorage.setItem(this.STORAGE_KEY, JSON.stringify(timers));
        } catch (e) {
          console.error('保存定时器数据失败:', e);
        }
      }

      // 清除所有定时器数据
      static clearTimers() {
        localStorage.removeItem(this.STORAGE_KEY);
      }
    }

    // 计时器数据存储
    let timers = TimerStorage.loadTimers();
    let timerId = timers.length > 0 ? Math.max(...timers.map(t => t.id)) : 0;
    // 添加计时器
    function addTimer() {
      const taskName = document.getElementById('taskName').value;
      const lastExecutionStr = document.getElementById('lastExecution').value;
      const intervalMinutes = parseInt(document.getElementById('intervalMinutes').value);

      if (!taskName || !lastExecutionStr || isNaN(intervalMinutes) || intervalMinutes <= 0) {
        alert('请输入有效的事项、最近执行时间和间隔时间');
        return;
      }

      const lastExecution = new Date(lastExecutionStr);
      const nextExecution = new Date(lastExecution.getTime() + intervalMinutes * 60000);

      const timer = {
        id: ++timerId,
        taskName: taskName,
        lastExecution: lastExecution,
        intervalMinutes: intervalMinutes,
        nextExecution: nextExecution
      };

      timers.push(timer);
      TimerStorage.saveTimers(timers); // 添加这行
      renderTimers();

      // 重置表单
      document.getElementById('taskName').value = '';
    }

    // 删除计时器
    function deleteTimer(id) {
      timers = timers.filter(timer => timer.id !== id);
      TimerStorage.saveTimers(timers); // 添加这行
      renderTimers();
    }

    // 完成计时器任务
    function completeTimer(id) {
      const timer = timers.find(t => t.id === id);
      if (!timer) return;

      // 更新最近执行时间为当前时间
      const now = new Date();
      timer.lastExecution = now;

      // 重新计算下次执行时间
      timer.nextExecution = new Date(now.getTime() + timer.intervalMinutes * 60000);

      // 保存并重新渲染
      TimerStorage.saveTimers(timers);
      renderTimers();

      // 显示完成通知
      showNotification(`任务 "${timer.taskName}" 已完成，下次执行时间已更新`, 5000);
    }


    // 渲染计时器列表
    function renderTimers() {
      // 按下次执行时间升序排序
      timers.sort((a, b) => a.nextExecution - b.nextExecution);

      const tbody = document.getElementById('timersList');
      tbody.innerHTML = '';

      const now = new Date();

      timers.forEach(timer => {
        const row = document.createElement('tr');

        // 判断是否到达执行时间（当前时间 >= 下次执行时间）
        const isDue = now >= timer.nextExecution;

        // 根据是否到期决定是否显示完成按钮
        const actionButtons =  isDue ?
          `<button class="edit-btn" onclick="completeTimer(${timer.id})">完成</button>
           <button class="delete-btn" onclick="deleteTimer(${timer.id})">删除</button>` :
          `<button class="delete-btn" onclick="deleteTimer(${timer.id})">删除</button>`;

        row.innerHTML = `
          <td>${timer.taskName}</td>
          <td>${formatDate(timer.lastExecution)}</td>
          <td>${timer.intervalMinutes}</td>
          <td>${formatDate(timer.nextExecution)}</td>
          <td>
            ${actionButtons}
          </td>
        `;

        tbody.appendChild(row);
      });
    }


    // 格式化日期时间（精确到秒）
    function formatDate(date) {
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(/\//g, '-');
    }

    // 检查计时器
    function checkTimers() {
      const now = new Date();
      let needSave = false; // 添加标志位
      timers.forEach(timer => {
        if (now >= timer.nextExecution) {
          // 触发通知
          showNotification(`任务 "${timer.taskName}" 到达执行时间！`);

          // 播放音频
          const audio = document.getElementById('alertSound');
          audio.play().catch(e => console.log('音频播放失败:', e));

          // 更新计时器
          /*timer.lastExecution = new Date();
          timer.nextExecution = new Date(timer.lastExecution.getTime() + timer.intervalMinutes * 60000);*/
          needSave = true; // 设置标志位
        }
      });
      if (needSave) { // 只有在需要时才保存
        TimerStorage.saveTimers(timers);
        renderTimers();
      }
    }

    // 显示通知
    function showNotification(message, duration = 0) {
      const notification = document.getElementById('notification');
      const notificationText = document.getElementById('notificationText');

      notificationText.textContent = message;
      notification.style.display = 'block';

      // 如果传入了持续时间，则在指定时间后自动隐藏
      if (duration > 0) {
        setTimeout(() => {
          notification.style.display = 'none';
        }, duration);
      }
    }

    function setDefaultTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');

      document.getElementById('lastExecution').value = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
    }

    setDefaultTime();
    renderTimers(); // 添加这行来渲染已存储的定时器
    // 初始化
    setInterval(checkTimers, 1000);

  </script>
</body>
</html>
